package com.haohuo.util;

import com.haohuo.config.constans.TraceConstans;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author: pk.zhang
 * @Date: 2021/3/12 13:01
 */
public class ThreadMdcUtil {

    /**
     * 设置MDC trace
     */
    public static void setTraceIdIfAbsent() {
        if (MDC.get(TraceConstans.TRACEID_KEY) == null) {
            MDC.put(TraceConstans.TRACEID_KEY, String.valueOf(TraceIDUtil.incrementAndGet()));
        }
    }


    /**
     * 对Callable类型线程进行包装
     *
     * @param callable
     * @param context
     * @param <T>
     * @return
     */
    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    /**
     * 对Runnable类型线程进行包装
     *
     * @param runnable
     * @param context
     * @return
     */
    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }

}
